import { listPagedDatasetEntriesBuild, createDatasetEntryBuild,  getDatasetEntryBuild, updateDatasetEntryBuild, deleteDatasetEntryBuild } from "@api/dataset/entry";
import { hasDatasetEntrySubscribe, getDatasetEntrySubscribe, setDatasetEntrySubscribe, getDatasetEntryInSubscribe, type ListDatasetEntriesParam } from "@entity/dataset/entry";
import { get as getVal } from "svelte/store";

export const listDatasetEntries = async (datasetCode: string, val: ListDatasetEntriesParam = {parent: "/"}, append: boolean = false) => {
  let list = getVal(getDatasetEntrySubscribe(datasetCode))
  const o = await listPagedDatasetEntriesBuild(datasetCode)(val);
  if (append) {
    list.rows.push(...o.rows)
    list.total = o.total;
  } else {
    list = o
  }
  setDatasetEntrySubscribe(datasetCode, list);
};

export const createDatasetEntry = async (datasetCode: string, val: any) => {
  const datasetEntry = await createDatasetEntryBuild(datasetCode)(val)
  const o = getVal(getDatasetEntrySubscribe(datasetCode))
  o.rows.push(datasetEntry)
  setDatasetEntrySubscribe(datasetCode, o);
  return datasetEntry;
}

export const updateDatasetEntry = async (datasetCode: string, val: any) => {
  const datasetEntry = await updateDatasetEntryBuild(datasetCode)(val)
  const o = getVal(getDatasetEntrySubscribe(datasetCode))
  let idx = o.rows.findIndex(v => v.id === datasetEntry.id)
  // console.log('before updated:', idx, JSON.stringify(val))
  o.rows.splice(idx, 1, datasetEntry)
  setDatasetEntrySubscribe(datasetCode, o);
  return datasetEntry;
}

export const deleteDatasetEntry = async (datasetCode: string, val: any) => {
  const datasetEntry = await deleteDatasetEntryBuild(datasetCode)(val)
  /// 作为数据源已经在datable里删除了
  // const o = getVal(getDatasetEntrySubscribe(datasetCode))
  // console.log('o.rows:',o.rows.length)
  // let idx = o.rows.findIndex(v => v.id === datasetEntry.id)
  // o.rows.splice(idx, 1)
  // console.log('o.rows 2:',o.rows.length)
  // // {total: 0, rows: []}
  // setDatasetEntrySubscribe(datasetCode, o);
  return datasetEntry;
}

export const getDatasetEntry = async (datasetCode: string, entryId: number) => {
  let datasetEntry = getDatasetEntryInSubscribe(datasetCode)(entryId);
  if (!datasetEntry) {
    datasetEntry = await getDatasetEntryBuild(datasetCode)(entryId);
    const o = getVal(getDatasetEntrySubscribe(datasetCode))
    o.rows.push(datasetEntry)
    setDatasetEntrySubscribe(datasetCode, o);
  }
  return datasetEntry
}